package com.example.springboot.utils;


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 文件加密
 */
public class Security {
    /**
     * 异或加密
     * @param sourceFilePath  源文件
     * @param targetFilePath   加密文件
     * @throws IOException      异常
     */
    public static void security(String sourceFilePath,String targetFilePath) throws IOException {
        File sourceFile = new File(sourceFilePath);
        File targetFile = new File(targetFilePath);

        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        try{
            inputStream = new FileInputStream(sourceFile);
            byte[] buffer = new byte[1024];
            int len = 0;
            outputStream = new FileOutputStream(targetFile);
            while((len = inputStream.read(buffer))>0){
                byte[] outputBuffer = new byte[len];
                //分别对每个字节进行异或操作
                for(int i=0;i<len;i++){
                    byte b = buffer[i];
                    b = (byte) (b ^ 25);
                    outputBuffer[i] = b;
                }
                outputStream.write(outputBuffer,0,len);
            }
        }finally{
            if(inputStream != null){
                inputStream.close();
            }
            if(outputStream != null){
                outputStream.close();
            }
        }
    }
}
